package com.smyx.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

@Slf4j
public class ZooKeeperClientTest {

    private ZooKeeper zkClient;

    @Before
    public void init() throws IOException {
        String connectionIp = "vm110:2181,vm111:2181,vm112:2181";
        int sessionTimeout = 3000;
        zkClient = new ZooKeeper(connectionIp, sessionTimeout, watchedEvent -> {
            log.info(">>>>>>>>>>>>>>>> server watchedEvent........");
        });
    }

    @Test
    public void create() throws InterruptedException, KeeperException {
        String node = zkClient.create("/servers", "servers".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        log.info(">>>>>>>>>>>>>>>> server 新创建节点: {}", node);
    }

    @Test
    public void listening() throws InterruptedException, KeeperException {
        List<String> children = zkClient.getChildren("/", true);
        children.forEach(System.out::println);
    }

}
